package com.tdk.wifidirectserver.adapter


import android.net.nsd.NsdServiceInfo
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.tdk.wifidirectserver.databinding.FragmentServerItemBinding


//生成一个RecyclerView的适配器 用于显示蓝牙设备列表
class ServerInfoAdapter(diffCallback: ItemCallback<NsdServiceInfo>) :
    ListAdapter<NsdServiceInfo, NsdServiceInfoViewHolder>(diffCallback) {
    val TAG = "ServerInfoAdapter"

    var onItemClickListener: ((NsdServiceInfo) -> Unit)? = null

    var onItemLongClickListener: ((NsdServiceInfo) -> Unit)? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NsdServiceInfoViewHolder {
        Log.d(TAG, "onBindViewHolder:")
        val binding = FragmentServerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return NsdServiceInfoViewHolder(binding)
    }

    override fun onBindViewHolder(holder: NsdServiceInfoViewHolder, position: Int) {
        val device = getItem(position)
        Log.d(TAG, "onBindViewHolder:   $device")
        holder.bind(device)
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(device)
        }
        holder.itemView.setOnLongClickListener {
            onItemLongClickListener?.invoke(device)
            true
        }
    }
}

//生成一个ViewHolder 用于显示蓝牙设备列表
class NsdServiceInfoViewHolder(private val binding: FragmentServerItemBinding) : RecyclerView.ViewHolder(binding.root) {
    fun bind(serviceInfo: NsdServiceInfo) {
        binding.content.text = serviceInfo.toString()
    }

}

class NsdServiceInfoDiff : ItemCallback<NsdServiceInfo>() {
    override fun areItemsTheSame(oldItem: NsdServiceInfo, newItem: NsdServiceInfo): Boolean {
        return oldItem.serviceName == newItem.serviceName && oldItem.serviceType == newItem.serviceType && oldItem.port == newItem.port
    }


    override fun areContentsTheSame(oldItem: NsdServiceInfo, newItem: NsdServiceInfo): Boolean {
        return oldItem.serviceName == newItem.serviceName && oldItem.serviceType == newItem.serviceType && oldItem.port == newItem.port

    }
}


